import ActivityData from '../models/activityData.js';
import Result from '../utils/result.js';
import { Op } from 'sequelize';

const activityDataService = {
  async getTodayActivity(userId) {
    try {
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);

        const activityData = await ActivityData.findOne({
            where: {
                userId,
                collectTime: {
                    [Op.between]: [today, tomorrow],
                },
            },
        });

        if (!activityData) {
            return Result.notfound('No activity data found for today');
        }

        return Result.success({
            steps: activityData.steps,
            distance: activityData.distance,
            calories: activityData.calories
        }, 'Get today activity data successfully');
    } catch (error) {
        return Result.error(error.message);
    }
  },
  async getHistoryActivity(userId, startDate, endDate) {
    try {
        const activityData = await ActivityData.findAll({
            where: {
                userId,
                collectTime: {
                    [Op.between]: [startDate, endDate],
                },
            },
        });

        if (!activityData) {
            return Result.notfound('No activity data found for the specified date range');
        }

        return Result.success(activityData, 'Get history activity data successfully');
    }catch(error){
        return Result.error(error.message);
    }
  },
  async getActivityStatistics(userId, period) {
    try {
      const { start, end } = getDataRange(period);
      const result = await this.getHistoryActivity(userId, start, end);

      if (!result.data || result.data.length === 0) {
        return Result.notfound('No activity data found');
      }

      // 过滤有效数据
      const validData = result.data.filter(item => 
        item && 
        typeof item.steps === 'number' && 
        !isNaN(item.steps) && 
        item.steps >= 0 && 
        item.collectTime
      );

      if (validData.length === 0) {
        return Result.error('No valid activity data available');
      }

      // 按时间排序
      const sortedData = validData.sort((a, b) => new Date(a.collectTime) - new Date(b.collectTime));

      if (period === 'day') {
        // 计算今日统计数据
        const totalSteps = sortedData.reduce((sum, item) => sum + item.steps, 0);
        const totalDistance = sortedData.reduce((sum, item) => sum + Number(item.distance), 0);
        const totalActiveTime = sortedData.reduce((sum, item) => sum + item.activeTime, 0);
        const targetSteps = 5000; // 默认目标步数
        const progress = Math.min(Math.round((totalSteps / targetSteps) * 100), 100);

        // 按时间段分组（6-22点，每2小时一个时段）
        const timeSlots = ["6-8", "8-10", "10-12", "12-14", "14-16", "16-18", "18-20", "20-22"];
        const hourlyData = Array(8).fill(0);

        sortedData.forEach(item => {
          const hour = new Date(item.collectTime).getHours();
          const slotIndex = Math.floor((hour - 6) / 2);
          if (slotIndex >= 0 && slotIndex < 8) {
            hourlyData[slotIndex] += item.steps;
          }
        });

        // 生成建议
        const advice = generateAdvice(totalSteps, totalActiveTime, targetSteps);

        return Result.success({
          steps: totalSteps,
          distance: totalDistance.toFixed(1),
          activeMinutes: totalActiveTime,
          progress,
          target: targetSteps,
          advice,
          hourlyData: {
            categories: timeSlots,
            series: [{
              name: "步数",
              data: hourlyData
            }]
          }
        }, '统计今日活动数据成功');
      } else if (period === 'week') {
        // 按天分组数据
        const dailyData = {};
        const weekDays = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        const targetSteps = 5000; // 默认目标步数

        sortedData.forEach(item => {
          const day = new Date(item.collectTime).getDay();
          const dayName = weekDays[day === 0 ? 6 : day - 1];
          
          if (!dailyData[dayName]) {
            dailyData[dayName] = {
              steps: 0,
              distance: 0,
              activeTime: 0
            };
          }
          
          dailyData[dayName].steps += item.steps;
          dailyData[dayName].distance += Number(item.distance);
          dailyData[dayName].activeTime += item.activeTime;
        });

        // 计算周统计数据
        const days = weekDays.map(dayName => {
          const dayData = dailyData[dayName] || { steps: 0, distance: 0, activeTime: 0 };
          return {
            name: dayName,
            steps: dayData.steps,
            distance: dayData.distance.toFixed(1),
            activeTime: dayData.activeTime,
            complete: dayData.steps >= targetSteps
          };
        });

        const totalSteps = days.reduce((sum, day) => sum + day.steps, 0);
        const avgSteps = Math.round(totalSteps / 7);
        const completeDays = days.filter(day => day.complete).length;
        const longestActive = Math.max(...days.map(day => day.activeTime));
        const bestDay = days.reduce((best, current) => 
          current.steps > best.steps ? current : best
        ).name;

        return Result.success({
          avgSteps,
          totalSteps,
          completeDays,
          longestActive,
          bestDay,
          days: days.map(day => ({
            name: day.name,
            complete: day.complete
          })),
          trendData: {
            categories: weekDays,
            series: [{
              name: "步数",
              data: days.map(day => day.steps)
            }]
          }
        }, '统计本周活动数据成功');
      }

      return Result.error('Invalid period');
    } catch (error) {
      console.error('Error in getActivityStatistics:', error);
      return Result.error(error.message);
    }
  }
};

// 辅助函数：生成活动建议
function generateAdvice(steps, activeTime, target) {
  const progress = (steps / target) * 100;
  
  if (progress >= 100) {
    return "恭喜您已完成今日活动目标！建议保持当前的活动习惯，注意适当休息。";
  } else if (progress >= 80) {
    return "您已经接近完成今日活动目标，建议再增加一些轻松的活动，如散步或伸展运动。";
  } else if (progress >= 50) {
    return "今日活动量已达到建议的50%以上，建议下午可适当增加10-15分钟的活动时间。";
  } else if (progress >= 30) {
    return "今日活动量偏低，建议增加活动时间，可以选择散步、做家务等轻度活动。";
  } else {
    return "今日活动量明显不足，建议尽快开始活动，可以从简单的散步开始。";
  }
}

// 辅助函数：获取数据范围
function getDataRange(period) {
  const now = new Date();
  if (period === 'day') {
    return {
      start: new Date(now.setHours(0, 0, 0, 0)),
      end: new Date(now.setHours(23, 59, 59, 999))
    };
  } else if (period === 'week') {
    const start = new Date(now);
    start.setDate(now.getDate() - 6); // 从6天前开始
    start.setHours(0, 0, 0, 0);
    
    const end = new Date(now);
    end.setHours(23, 59, 59, 999);
    
    return { start, end };
  }
  return { start: now, end: now };
}

export default activityDataService;